package utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.function.Function;


@Component
public class JwtTokenUtil implements Serializable {

    @Value("${system.jwt.signKey}")
    private String jwtSignKey;

    @Value("${system.jwt.expireTime}")
    private Long jwtExpireTime;

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public Date getIatFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    public Date getLastLoginTimeFromToken(String token) {
        final Claims claims = getAllClaimsFromToken(token);
        if (claims.get("lastLoginTime") == null) {
            return null;
        }
        return new Date((Long)claims.get("lastLoginTime"));
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtSignKey)
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token, Date lastModifyPasswordTime) {
        final Date expiration = getExpirationDateFromToken(token);
        final Date iat = getIatFromToken(token);
        return expiration.before(new Date()) || (lastModifyPasswordTime != null && iat.before(lastModifyPasswordTime));
    }

    public String generateToken(String username, Date lastLoginTime) {
        return doGenerateToken(username, lastLoginTime);
    }

    private String doGenerateToken(String subject, Date lastLoginTime) {
        Claims claims = Jwts.claims().setSubject(subject);
        claims.put("lastLoginTime", lastLoginTime);

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpireTime * 1000))
                .signWith(SignatureAlgorithm.HS256, jwtSignKey)
                .compact();
    }

    public Boolean validateToken(String token, Date lastModifyPasswordTime) {
        final String username = getUsernameFromToken(token);
        return !isTokenExpired(token, lastModifyPasswordTime);
    }

}
